package com.flyme.common.security.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by xinxingegeya on 2016/11/30.
 */
public class ProxiedFilterChain implements FilterChain {
    private AtomicInteger chainCount;
    private FilterChain orig;
    private List<Filter> filters;

    public ProxiedFilterChain(FilterChain orig, List<Filter> filters) {
        if (orig == null) {
            throw new NullPointerException("original FilterChain cannot be null.");
        }
        this.orig = orig;
        this.filters = filters;
        this.chainCount = new AtomicInteger(0);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (this.filters == null || this.filters.size() == this.chainCount.get()) {
            this.orig.doFilter(request, response);
        } else {
            this.filters.get(this.chainCount.getAndIncrement()).doFilter(request, response, this);
        }
    }
}
